package com.jnu.assistant.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jnu.assistant.mapper.LoginMapper;
import com.jnu.assistant.pojo.Code2SessionResponse;
import com.jnu.assistant.pojo.UserOpenId;
import com.jnu.assistant.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.appsecret}")
    private String appSecret;

    private Code2SessionResponse mapToSessionResponse(String response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(response, Code2SessionResponse.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("解析响应失败", e);
        }
    }

    @Override
    public Code2SessionResponse code2Session(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        if (response.getStatusCode().isError()) {
            throw new RuntimeException("请求失败，状态码: " + response.getStatusCode().value());
        }

        return mapToSessionResponse(response.getBody());
    }

    @Autowired
    LoginMapper loginMapper;

    @Override
    public Integer getUserId(String openid) {
        return loginMapper.getUserId(openid);
    }

    @Override
    public void insertId(UserOpenId userOpenId) {
        loginMapper.insertId(userOpenId);
    }
}